<?php

/**
 * cmsField form.
 *
 * @package    cms
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class cmsForm extends BaseFormDoctrine
{  
  
  private $filesToDeleteInDoSave = array();


  public function configure()
  {       
    
    $fields = cmsFieldTable::getInstance()->getHeadersQuery()->andWhere('c.allow_form = ?', true)->fetchArray();
    
    $this->setConfiguration($fields);    
  
    $this->widgetSchema->setNameFormat('cms_'.sfContext::getInstance()->getRequest()->getParameter('table').'[%s]');
  }
  
  public function getActionUrlParams()
  {
    
    $urlParams['table'] = sfContext::getInstance()->getRequest()->getParameter('table');
    $urlParams['action'] = ($this->getObject()->isNew() ? 'create' : 'update');
    if(!$this->getObject()->isNew())
    {
      $urlParams['id']= $this->getObject()->getId();
    }
    
    return $urlParams;
  }  
  
  private function setConfiguration($fields)
  {
    sfProjectConfiguration::getActive()->loadHelpers(array('I18N'));
    $request = sfContext::getInstance()->getRequest();   
    
    $menuTable = $request->getParameter('table');
    
    foreach($fields as $key => $field)
    {       
      $fieldType = $field['cmsFieldType']['name'];
      
      if($fieldType == 'text')
      {          
        if($field['subtype'] == 'date')
        {
          $this->setWidget($field['col'], new sfWidgetFormJQueryDate());
        }        
        else if($field['subtype'] == 'rich')
        {
          $this->setWidget($field['col'], new sfWidgetFormTextareaTinyMCE(array('width'  => 550,'height' => 350)));
          $this->setValidator($field['col'], new sfValidatorString());
        }
        else
        {
          $this->setWidget($field['col'], new sfWidgetFormInput());
          $this->setValidator($field['col'], new sfValidatorString());
        }
      }
      else if($fieldType == 'boolean')
      {
        $this->setWidget($field['col'], new sfWidgetFormChoice(array('choices' => array(1=> __('yes'), 0=> __('no')))));
        $this->setValidator($field['col'], new sfValidatorBoolean(array('required' => true)));
      }
      else if($fieldType == 'choice')
      {              
        $relationName = Cms::getRelationNameFormLocal(sfConfig::get('app_soulution_name') . $menuTable, $field['col']);
        
        $this->setWidget($field['col'], new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName($relationName))));
        $this->setValidator($field['col'], new sfValidatorDoctrineChoice(array('model' => $this->getRelatedModelName($relationName))));
      }
      else if($fieldType == 'media')
      {                       
        $isImage = false;
        
        if($field['subtype'] == 'image' || $field['subtype'] == 'images')
        {
          $isImage = true;
        }
        
        if($field['subtype'] == 'file' || $field['subtype'] == 'image')
        { 
          $array = $this->getObject()->toArray();
        
          $value = Doctrine_Core::getTable($field['relation'])->find($array[$field['col']]);        

          eval('$subForm = new '.$field['relation'].'Form($value);');        
          
          $subForm->useFields(array('name', 'description'));
          
          $subForm->setWidget('name', new sfWidgetFormInputFileEditable(array(
            'with_delete' => false,
            'file_src'  => DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $field['relation'] . DIRECTORY_SEPARATOR . $value . '_m.' . $value['extension'],
            'is_image'  => $isImage,
            'edit_mode' => !$this->isNew(),
            'template'  => '<div class="uploadify">%file%<br />%input%</div>'
          )));         
          $subForm->setValidator('name', new sfValidatorFile( array(
            'required' => false,
            'path'       => sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . $field['relation'] . DIRECTORY_SEPARATOR,
            'mime_types' => 'web_images',
            'max_size' => '1024000',
            'validated_file_class' => 'cmsValidatedFile'
          )));          
          
          // konieczne aby nie wywalało błedu (nadprogramowe pole "extension")przy próbie dopisanie rozszerzenia w $this->save()
          // TODO: jak się da to jakoś to wywalić bo zaśmieca
          $subForm->setValidator('extension', new sfValidatorString(array('required' => false)));

          $subForm->setWidget('description', new sfWidgetFormInput());        
          $subForm->setValidator('description', new sfValidatorString());
          
          $subFormName=$field['relation'];

        }        
        else if($field['subtype'] == 'files' || $field['subtype'] == 'images')
        {       
            $subForm = new sfForm();

            $q = Doctrine_Query::create()->from($field['tab'])->select('*')->where('parent_id = ?',$this->getObject()->getId())->orderBy('position');
            
            $files = $q->fetchArray();
 
            $subForm->setWidget('file', new sfWidgetFormUploadify(array(
                'multi'=>true, 
                'files' => $files, 
                'field'=>$field, 
                'uploadDirectory'=>DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $field['tab'] . DIRECTORY_SEPARATOR
            ), array('disabled' => 'disabled')));   
 
            $subForm->widgetSchema['file']->setLabel(false);
            
            $subFormName=$field['tab'].$field['id'];
        }          

        $this->embedForm($subFormName, $subForm);
        $this->widgetSchema[$subFormName]->setLabel($field['Translation'][$request->getParameter('sf_culture')]['name']);
      }
    }
  }  
  
  public function save($con = null)
  {
    $fields = cmsFieldTable::getInstance()->getHeadersQuery()->andWhere('c.allow_form = ?', true)->fetchArray();
    
    $request = sfContext::getInstance()->getRequest();  
    
    $params = sfContext::getInstance()->getRequest()->getParameter($this->getName());
    
    print_r($params);
    foreach($fields as $field)
    {     
      if($field['subtype'] == 'image')
      {        
        // kurwa nie podoba mi się to!!
        // TODO: pomyśleć o przeniesieniu całego tego if do cmsValidatedFile()->save()  
        $newFile = $this->getValue($field['relation']);
     
        $oldFile = $this->getObject()->getCmsFile();
        
        // sprawdza, czy w ogóle przesyłany jest nowy plik, bo jak nie to pominąć dalczą część, która w takim przypadku wygeneruje błąd przy 'pathinfo($newFile['name']->getOriginalName())'
        if($newFile['name'])
        {
          $fileDirectoryPath = sfConfig::get('sf_upload_dir') . DIRECTORY_SEPARATOR . $request->getParameter('table') . DIRECTORY_SEPARATOR;          

          $this->filesToDeleteInDoSave = array_merge($this->filesToDeleteInDoSave, glob($fileDirectoryPath .$oldFile['name']."_?.".$oldFile['extension']));   

          $pathInfo = pathinfo($newFile['name']->getOriginalName());
          $params[$field['relation']]['extension'] = $pathInfo['extension'];

          // nadal mi się to nie podoba ale co zrobić? - działa
          $this->filesToDeleteInDoSave[] = $fileDirectoryPath . Cms::slugify($pathInfo['filename']);
        }
        else
        {
          // jeżeli nie dodajemy nowego pliku to ustawia takie same rozszerzenie jak bylo zapisane bo inaczej usówa
          // TODO: zobaczyć czy da się jakoś zrobić żeby nie ruszało przy save() extension jeśli plik nie jest zmieniany ale bez ingerowaniu w model czyli cmsFile.class.php - nie wolno!
          $params[$field['relation']]['extension'] = $oldFile->getExtension();
        }
      }
//      else if($field['subtype'] == 'images' || $field['subtype'] == 'files')
//      {
//        unset($params[$field['tab'].$field['id']]);
//      }
    }    
    
    $this->bind($params, sfContext::getInstance()->getRequest()->getFiles($this->getName()));
    
    return parent::save($con = null);;
  }
  
  protected function doSave($con = null)
  {
    parent::doSave($con);    
    
    array_map('unlink', $this->filesToDeleteInDoSave);   
  }

  public function getModelName()
  {
    return 'cms'. ucfirst(sfContext::getInstance()->getRequest()->getParameter('table'));
  }  
}